package com.byq.mm.abstractx.cluster.server;


import com.byq.mm.abstractx.cluster.server.access.SecuredServer;
import com.byq.mm.abstractx.device.Device;
import com.byq.mm.abstractx.engine.CoreEnvironment;
import com.byq.mm.abstractx.protocol.Defination;
import com.byq.mm.abstractx.protocol.Interaction;


import java.util.HashMap;
import java.util.Map;

public class ServerDeviceManager extends SecuredServer {
	CoreEnvironment env;
	Device device;

	ServerIdentifier id;
	Map<String, DeviceServer> servers = new HashMap<String, DeviceServer>();
	
	DeviceServer rootServer;
	public ServerDeviceManager(CoreEnvironment env) {
		super(env);
		this.env = env;
		id = new ServerIdentifier(null, null);
	}
	public ServerIdentifier getId() {
		return id;
	}
	public void reset(Device device)
	{
		this.device = device;
		rootServer =  new DeviceServer(device, env);
		servers.put(device.getId(),rootServer);
		for(Device d : device.getSubdevices()){
			servers.put(d.getId(), new DeviceServer(d, env));
		}
	}
	public void addDirectChildren(Device dc){
		device.getSubdevices().add(dc);
		DeviceServer directChild = new DeviceServer(dc, env);
		servers.put(dc.getId(),directChild);
		for(Device d : dc.getSubdevices()){
			servers.put(d.getId(), new DeviceServer(d, env));
		}
	}
	public Device getLocalServerDevice(){
		return device;
	}
	private SmartServer getSecureDeviceServer(String deviceId){
		DeviceServer ds =  servers.get(deviceId);
		if(ds == null)
			return null;
		return ds.getServerAccessController();
	}
	public DeviceServer getDeviceServer(String deviceId){
		return  servers.get(deviceId);
	
	}
	public void accepted(String jid){

		for(DeviceServer e : servers.values())
			for(ClusterServer cs : e.getClusterServers())
				cs.getAccessController().accepted(jid);
		 env.getEventCenter().notifyDeviceChange();
	}

	
	public void offer(String jid){

		Device me = env.getServerDeviceManager().getLocalServerDevice();
		Defination dd = new Defination();
		dd.offer(me);
		env.getExtensionManager().sendDefination(dd, jid);
	}
	public void sendAcceptAndDefine(String id) {
		
		Defination dd = new Defination();
		dd.accept(env.getServerDeviceManager().getLocalServerDevice());
		env.getExtensionManager().sendDefination(dd, id);
	}

	public void request(String user) {
		Defination dd = new Defination();
		dd.request();
		env.getExtensionManager().sendDefination(dd, user);
		
	}

	@Override
	public boolean onCommand(Interaction i, String transport) {
		SmartServer server = getSecureDeviceServer(i.to);
		if(server == null)
			return false;
		return server.onCommand(i, transport);
		
	}
}
